package com.yz.crm.passport.action;

import com.yz.common.model.RemoteInteractObject;
import com.yz.common.util.Functions;
import com.yz.crm.passport.constant.PassportConst;
import com.yz.crm.passport.model.SessionUser;
import com.yz.crm.passport.service.PassportService;

import com.yz.crm.weixin.util.WechatUtils;
import com.yz.util.Constants;
import com.yz.util.WebUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.javassist.compiler.MemberResolver;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 用户登录
 * Created by DOVE on 2017/5/15 0015.
 */
@Controller
@RequestMapping("/passport")
public class LoginAction {
    private static final Log log = LogFactory.getLog(LoginAction.class);
    @Resource
    private UserResolver userResolver;
    @Resource
    private PassportService passportService;

    @RequestMapping("/wLogin")
    public String wLogin(HttpServletRequest request, HttpServletResponse response,
                         String openId, HttpSession session) {
        String ip = WebUtils.getIp(request);
        openId = StringUtils.isNotEmpty(openId) ? openId : WebUtils.getCookie(request, Constants.COOKIE_USER_OPENID);
        String userId = WebUtils.getCookie(request, Constants.COOKIE_USER_THIRDPARTY_ID);
        boolean isWechat = WebUtils.isWeChatRequest(request);
        log.info("ip:" + ip + ",openId:" + openId + ",userId:" + userId + ",isWechat:" + isWechat);
        //根据cookie 获取用户登陆信息并跳转到请求页面
        if (userResolver.loginByCookie(request, response, session)) {
            return WebUtils.calRefererUrlToRedirect(request);
        }
        if (StringUtils.isEmpty(openId) && isWechat) {
            //进入授权页面获取用户openId
            String authUrl = WebUtils.getRequestContentUrl(request)
                    + "/passport/wLogin";
            authUrl = Functions.urlEncode(authUrl, "UTF-8");
            String willOpenUrl = WechatUtils.getAuthRedirectUrl(authUrl, WebUtils.getRequestContentUrl(request) + "/userRedirectService");
            log.info("----->>> ip=" + ip + ",willOpenUrl=" + willOpenUrl);
            return "redirect:" + willOpenUrl;
        }
        return  "test/upload";
    }

    /**
     * 公司登录
     *
     * @return
     */
    @RequestMapping("/login")
    private String login(HttpServletRequest request, ModelMap modelMap) {
        String openId = request.getParameter("openId");
        String username = WebUtils.getCookie(request, PassportConst.COOKIE_PASS);
        modelMap.addAttribute("username", username);
        return "/passport/login";
    }

    @RequestMapping(value = "/doLogin", method = {RequestMethod.POST})
    @ResponseBody
    private RemoteInteractObject doLogin(
            String username,
            String password,
            String imgCheckCode,
            @RequestParam(value = "userNameCheck", required = false) boolean userNameCheck,
            HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        RemoteInteractObject ValidResult = new RemoteInteractObject();
        try {
            String imgCode = (String) session.getAttribute(PassportConst.SESSION_KEY_CHECK_CODE);
            if (!imgCheckCode.equalsIgnoreCase(imgCode)) {
                ValidResult.setMsgCode(100);
                ValidResult.setMsg("图形验证码错误！");
                return ValidResult;
            }
            SessionUser user = passportService.login(username, password);
            if (user == null) {
                ValidResult.setMsgCode(99);
                ValidResult.setMsg("用户名或者密码错误");

                return ValidResult;
            }
            String pass = null;
            //记住用户名
            if (userNameCheck) {
                pass = username;
                WebUtils.addCookie(request, response, PassportConst.COOKIE_PASS, pass, 7 * 24 * 3600, "cookiePath", null, null);
            } else {
                WebUtils.removeCookie(request, response, PassportConst.COOKIE_PASS, "cookiePath", null);
            }
            session.setAttribute(PassportConst.SESSION_KEY_USER, user);
            ValidResult.setMsgCode(PassportConst.CODE_SUCCESS);
            ValidResult.setSuccess(true);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ValidResult;
    }

}
